package root.electronclass.electronclass.personal.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import root.electronclass.electronclass.R
import java.text.DecimalFormat

/**
 *
 * @author Lokiy
 * @date 2025/6/15 22:40
 */
class HalfCircleScoreChart @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyle: Int = 0
) : View(context, attrs, defStyle) {

    private val df = DecimalFormat("0.#")
    var score: Float = 80f
        set(value) {
            field = value
            invalidate()
        }
    var maxScore: Int = 100

    private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
//        strokeCap = Paint.Cap.ROUND
        color = Color.parseColor("#FFE8F9FF")
        strokeWidth = 48f
    }
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
//        strokeCap = Paint.Cap.ROUND
        strokeWidth = 40f
    }
    private val scorePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = resources.getColor(R.color.c_093b5d)
        textSize = 24f
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD
    }
    private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = resources.getColor(R.color.c_093b5d_80)
        textSize = 14f
        textAlign = Paint.Align.CENTER
    }
    private val rectF = RectF()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val w = width.toFloat()
        val h = height.toFloat()
        val stroke = bgPaint.strokeWidth
        val radius = (w / 2).coerceAtMost(h) - stroke / 2
        val cx = w / 2
        val cy = h

        rectF.set(cx - radius, cy - radius, cx + radius, cy + radius)

        // 底色半圆
        canvas.drawArc(rectF, 180f, 180f, false, bgPaint)

        // 渐变进度半圆
        val sweep = 180f * (score / maxScore.toFloat())
        val shader = LinearGradient(
            rectF.left, rectF.bottom, rectF.right, rectF.top,
            intArrayOf(Color.parseColor("#FF19A6FF"), Color.parseColor("#FF37DEFF")),
            null, Shader.TileMode.CLAMP
        )
        progressPaint.shader = shader
        canvas.drawArc(rectF, 180f, sweep, false, progressPaint)

        // 中间分数
        canvas.drawText("${df.format(score)}分", cx, cy - scorePaint.textSize / 2 - 20, scorePaint)
        // 描述文字
        canvas.drawText("当前德育分", cx, cy - labelPaint.textSize / 2, labelPaint)
    }
}